package com.gxa.controller;

import com.github.pagehelper.PageHelper;
import com.gxa.entity.Mso;
import com.gxa.entity.Msoxq;
import com.gxa.entity.User;
import com.gxa.service.OrderService;
import com.gxa.utils.TimeUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping(value = "/order")
@CrossOrigin
@GlobalTransactional //全局事务
public class OrderController {
    //测试用的接口，已成功！

//    private FUserFeign fUserFeign;
//    @GetMapping("/add")
//    public R addOrder (String username,String password){
//        //运行的时候此语句没有执行而是直接执行的feign调用的接口，也就是说feign有最高执行优先级
//        System.out.println("账号："+username+"、密码："+password);
////        User user1=null;
//        //判断语句也没有用
////        if(username!=null && password!=null){
////            System.out.println("账号："+username+"、密码："+password);
////            user1=fUserFeign.login(username,password);
////        }
//        /*
//         注意：远程调用feign可以执行调用服务的接口，但是不会得到他返回的结果
//         实际执行的结果是真实有效的
//         */
//        User user1=fUserFeign.login(username,password);
//        return R.success(200,"远程调用结果值：=="+user1);
//    }
    @Autowired(required =false)
    private OrderService orderService;
//    @Autowired
//    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
//    @Autowired
//    private CarService carService;


    @PostMapping("/shopNow")
    public String shopNow(@RequestBody Map map){
        User user = (User) redisTemplate.opsForValue().get("user");
        if (user==null){
            return "请先登录用户后选购！";
        }
        String orderNumber = TimeUtils.getOrderNumber();
        List<Msoxq> msoxqs = new ArrayList<>();
//        Integer currentCount = (Integer)map.get("currentCount");
        Integer id =(Integer)map.get("id");        //商品id
        Integer iPrices = (Integer)map.get("iPrice"); //价格
        String iP=Integer.toString(iPrices);
        Double iPrice= new Double(iP);
        String pImg = (String) map.get("pImg"); //图片
        String pSn =(String) map.get("pSn"); //数量
        Msoxq msoxq = new Msoxq(null,orderNumber,1,id,
                iPrice,pImg,pSn);
        redisTemplate.opsForValue().set("shopNow_msoxq",msoxq);
        msoxqs.add(msoxq);
        Mso mso = new Mso(null,orderNumber,user.getName(),user.getTelephone(),TimeUtils.getTime(),
                "已付款",iPrice,user.getAddress(),user.getId(),"已发货",msoxqs);
        redisTemplate.opsForValue().set("order_mso",mso);
        redisTemplate.opsForValue().set("shopNow",1);
        return "ok";
    }
    /**
     * 获取订单详情里面的所有内容
     *
     * @param
     * @return
     */
    @GetMapping("/getOrder")
    public Mso getMsos(){
        //共享订单信息内容
        Mso mso=(Mso) redisTemplate.opsForValue().get("order_mso");
        //如果mso对象不为空的话，就可以直接返回，否则直接返回null
        if (mso == null) {
            return null;
        }
        //直接返回给订单页面
        return mso;
    }

    /**
     * 获取
     *
     * @param request
     * @return
     */
    @GetMapping("/getLoginUser")
    public User getLoginUser(HttpServletRequest request){
        //初始化session
        HttpSession session = request.getSession();
        //获取session里面的user对象
//        User user = (User) session.getAttribute("user");
        User user = (User) redisTemplate.opsForValue().get("user");
        //如果用户暂未登录的话就返回null
        if (user == null) {
            return null;
        }
        //返回一个user对象
        return user;
    }


    /**
     *  支付订单
     */
    @GetMapping("/payMoney")
    public Map payMoney(String msoid, Integer userid){
        Map map=new HashMap();
        map.put("mso_id",msoid);
        map.put("userid",userid);
        map.put("paystate","已付款");

        Integer shopNow=(Integer) redisTemplate.opsForValue().get("shopNow");
        //判断是否为立即选购的商品
        if(shopNow !=null && shopNow==1){
            Msoxq msoxq=(Msoxq) redisTemplate.opsForValue().get("shopNow_msoxq");
            Mso mso=(Mso) redisTemplate.opsForValue().get("order_mso");
            orderService.addToMsoXq(msoxq);
            orderService.addToMso(mso);
        }
        return map;
    }
    /**
     * 根据用户id查询mso产品集合
     */
    @GetMapping("/getMsoByUserid")
    public List<Mso> getMsoByUserid(@RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage,
                                    @RequestParam(value = "pageSize",defaultValue = "3") Integer pageSize
                                   ){
        User user=(User) redisTemplate.opsForValue().get("user");
        //获取用户的id号
        Integer userid = user.getId();
        //根据用户id查询mso订单集合
        PageHelper.startPage(currentPage,pageSize);
        List<Mso> msoList = orderService.getMsoByUserid(userid);

        //返回一个带有数据的给前端
        return msoList;
    }

    @GetMapping("/getMsoxqByMsoid/{msoid}")
    public String getMsoxqByMsoid(@RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage,
                                  @RequestParam(value = "pageSize",defaultValue = "3") Integer pageSize,
                                  @PathVariable String msoid, HttpServletRequest request){



        //初始化session对象
        HttpSession session = request.getSession();
        //分页工具根据msoid来查询我们的订单的详情
        PageHelper.startPage(currentPage,pageSize);
        redisTemplate.opsForValue().set("current_msoid",msoid);
        return "OK";
    }

    /**
     * 获取存在session域中的产品
     *
     * @param request
     * @return
     */
    @GetMapping("/pageMsoxq")
    public List<Msoxq> pageMsoxq(@RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage,
                                 @RequestParam(value = "pageSize",defaultValue = "3") Integer pageSize,
                                 HttpServletRequest request){
//        String msoid = (String) session.getAttribute("current_msoid");
        String msoid=(String) redisTemplate.opsForValue().get("current_msoid");
        System.out.println("订单的编号："+msoid);
        PageHelper.startPage(currentPage,pageSize);
        List<Msoxq> msoxqList = orderService.getMsoxqByMsoid(msoid);

        return msoxqList;
    }

    /**
     * 获取存在session域中的产品
     *
     * @param request
     * @return
     */
    @GetMapping("/getMsoxq")
    public List<Msoxq> getMsoxq(HttpServletRequest request){

        //初始化session
        HttpSession session = request.getSession();
        //获取session域中的内容
//        List<Msoxq> msoxqList = (List<Msoxq>) session.getAttribute("msoxq");
//        List<Msoxq> msoxqList=redisTemplate.opsForList().range("msoxq",0,-1);
        String msoid=(String) redisTemplate.opsForValue().get("current_msoid");
        List<Msoxq> msoxqList = orderService.getMsoxqByMsoid(msoid);
        return msoxqList;
    }

    @GetMapping("/getMsoCountByUserid")
    public Integer getMsoCountByUserid(HttpServletRequest request){

        //初始化session
        HttpSession session = request.getSession();
        //获取session域中的user
//        User user = (User) session.getAttribute("user");
//        User user=userService.querySession();
        User user=(User) redisTemplate.opsForValue().get("user");
        //根据用户id查询mso总记录数
        Integer current_totalPage = orderService.getMsoCountByUserid(user.getId());
        //返回总页数
        int totalPage = (int) (Math.ceil(current_totalPage*1.0/3));

        //mso的总页数
        return totalPage;
    }

    @GetMapping("/getMsoxqCountByMsoid")
    public Integer getMsoxqCountByMsoid(HttpServletRequest request){

//        List<Msoxq> msoxqList=redisTemplate.opsForList().range("msoxq",0,-1);
        String msoid=(String) redisTemplate.opsForValue().get("current_msoid");
        Integer current_totalPage = orderService.getMsoxqCountByMsoid(msoid);
        int totalPage = (int) (Math.ceil(current_totalPage*1.0/3));

        //mso的总页数
        return totalPage;
    }

    /**
     * 查询所有订单的方法
     *
     * @return
     */
    @GetMapping("/findAll")
    public List<Mso> findAll(@RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage,
                             @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){




        //返回一个分页好的集合分页操作
        PageHelper.startPage(currentPage,pageSize);
        return orderService.findAll();
    }

    /**
     * 返回订单总数
     *
     * @return
     */
    @GetMapping("/getTotalPage")
    public Integer getTotalPage(){

        //先获取总记录数
        Integer totalCount = orderService.getTotalCount();

        //计算总页数：总记录数 / 10 最后向上取整
        Integer totalPage = (int) Math.ceil(totalCount*1.0/10);

        //返回总页数
        return totalPage;
    }

    /**
     * 根据msoid删除订单
     *
     * @param msoid
     * @return
     */
    @GetMapping("/deleteByMsoid/{msoid}")
    public String deleteByMsoid(@PathVariable String msoid) {

        //根据订单号同时删除mso和msoxq表中的订单
        try {
            orderService.deleteByMsoid(msoid);
        } catch (Exception e) {
            return "ERROR";
        }

        return "OK";
    }

    /**
     * 根据订单msoid获取msoxq集合
     *
     * @param msoid
     * @return
     */
    @GetMapping("/getMsoxqByMsoid_admin/{msoid}")
    public List<Msoxq> getMsoxqByMsoid_admin(@PathVariable String msoid){
        //根据msoid来查询我们的msoxq的集合的内容
        List<Msoxq> msoxqList = orderService.getMsoxqByMsoid(msoid);
        //返回集合
        return msoxqList;
    }

    @GetMapping("/sendPro/{msoid}")
    public String sendPro(@PathVariable String msoid){

        try {
            //更具订单id更新货物的发货状态
            orderService.sendPro(msoid);
        } catch (Exception e) {
            return "ERROR";
        }

        return "OK";
    }

}
